package cc.yugu.yhdw.common.utils;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import java.security.MessageDigest;
/**
 * 加密工具（安全问题）
 *
 * @Date:Created in 2018/7/3 11:52
 * @Author:
 * @Modified By: zxj 2018/7/3 11:52
 */
public class CodecUtils {
    final static Logger logger = LogManager.getLogger(CodecUtils.class);
    // 密码前缀有含义
    static final String PASSWORD_DELTA_1 = "678CAC1884EC98A89E9A269671AEDC28";
    static final String PASSWORD_DELTA_2 = "678CAC33333ECsdfsdf1269671AEDC28";

    public static void main(String[] args) {
        System.out.println(password("admin"));
        System.out.println(password1("admin"));
        System.out.println(password2("admin"));
    }

    /**
     * WEB生成的密码直接调用password
     * @param src
     * @return
     */
    public static String password(String src) {
        return password2(password1(src));
    }

    /**
     * 客户APP传过来的密码要调用
     * @param src
     * @return
     */
    public static String password2(String src) {
        return md5(PASSWORD_DELTA_2 + sha(PASSWORD_DELTA_2 + src));
    }

    public static String password1(String src) {
        return md5(PASSWORD_DELTA_1 + sha(PASSWORD_DELTA_1 + src));
    }

    public static String sha(String src) {
        MessageDigest md;
        try {
            md = MessageDigest.getInstance("SHA");
            byte[] a = md.digest(src.getBytes("utf-8"));
            return byteToHex(a);

        } catch (Exception e) {
            e.printStackTrace();
            throw new IllegalArgumentException(e);
        }
    }

    public static String md5(String src) {
        MessageDigest md;
        try {
            md = MessageDigest.getInstance("MD5");
            byte[] a = md.digest(src.getBytes("utf-8"));
            return byteToHex(a);

        } catch (Exception e) {
            e.printStackTrace();
            throw new IllegalArgumentException(e);
        }
    }

    public static String byteToHex(byte[] a) {
        StringBuilder buf = new StringBuilder();

        for (int i = 0; i < a.length; i++) {
            if (a[i] < 0)
                buf.append(Integer.toHexString(a[i]&0xff));
            else if (a[i] < 16) {
                buf.append('0');
                buf.append(Integer.toHexString(a[i]));
            } else {
                buf.append(Integer.toHexString(a[i]));
            }
        }

        return buf.toString().toUpperCase();
    }
}
